package hydrap2p.library;

import hydrap2p.ServiceLocation;

import java.util.Map;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Represents one registered Metadater
 * @author Hufman
 *
 */
public class MetadaterThrift implements Metadater{
	private MetadataChecker.Client connection;
	private ServiceLocation location;
	
	/**
	 * Creates a new Metadater object, and tries to connect to it
	 * If it fails to cnonect, it will through an exception
	 * @param location
	 * @throws TException 
	 */
	public MetadaterThrift(ServiceLocation location) throws TException
	{
		// Special case for the Unit Test
		// Don't connect to null locations
		if (location==null)
			return;
		
		this.location=location;

		TTransport transport = new TSocket(location.address,location.port);
		transport.open();
		connection=new MetadataChecker.Client(new TBinaryProtocol(transport));
		
		if (!connection.supportedInterfaces().contains("MetadataChecker"))
			throw new TException("Module does not implement interface MetadataChecker");
		
	
	}
	
	/**
	 * Parses this filename for metadata
	 * Throws an exception if something bad happens, which usually signals that this metadater no longer works
	 * @param filename
	 * @return
	 * @throws TException
	 */
	public Map<String, String> parseMetadata(String filename) throws Exception
	{
		return connection.parseMetadata(filename);	
	}
}
